# -*- coding = utf-8 -*-
# @Time : 2021/12/22 9:22
# @Author : 龙王赘婿_彪少
# @File : demo08.py
# @Software: PyCharm

# 信号与槽

import sys
from PyQt5.QtCore import Qt, QObject, pyqtSignal
from PyQt5.QtWidgets import (QMainWindow, QLCDNumber, \
                             QSlider, QVBoxLayout, \
                             QApplication, QPushButton)


class Example(QMainWindow):
    def __init__(self):
        super().__init__()
        # self.init_01() # QWidget 改成 QMainWindow 布局失效
        # self.init_02()
        self.init_03()
        self.SHOW()

    # 信号与槽
    def init_01(self):
        lcd = QLCDNumber(self)
        sld = QSlider(Qt.Horizontal, self)

        vbox = QVBoxLayout()
        # 根据我学C++的经验，其实下面这句话指定了父类，就等价于self.setLayout()
        # vbox = QVBoxLayout(self)
        # vbox.addStretch(1)
        vbox.addWidget(lcd)
        vbox.addWidget(sld)
        self.setLayout(vbox)
        # 信号与槽
        sld.valueChanged.connect(lcd.display)

    def init_02(self):
        btn1 = QPushButton("Button 1", self)
        btn1.move(30, 50)

        btn2 = QPushButton("Button 2", self)
        btn2.move(150, 50)

        self.statusBar()

        btn1.clicked.connect(self.buttonClicked)
        btn2.clicked.connect(self.buttonClicked)

    def init_03(self):
        self.boj_c = Communicate()
        self.boj_c.closeApp.connect(self.close)

    def mousePressEvent(self, e) -> None:
        self.boj_c.closeApp.emit()

    def buttonClicked(self):
        sender = self.sender()
        self.statusBar().showMessage(sender.text() + " was pressed!")

    def SHOW(self):
        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle("Title")
        self.show()

    # 重写按键事件 把父类的函数重写了
    def keyPressEvent(self, e) -> None:
        if e.key() == Qt.Key_Escape:
            self.close()


class Communicate(QObject):
    closeApp = pyqtSignal()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
